package android.serialport.sample;

import android.os.SystemClock;
import android.serialport.api.SerialPort;
import android.serialport.utils.HexUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SerialPortCtrl {

    private InputStream mInputStream;
    private OutputStream mOutputStream;
    private SerialPort mSerialPort;
    private final ExecutorService mThreadPool = Executors.newFixedThreadPool(2);

    /**
     *
     * @param path 串口节点
     * @param baudRate 波特率
     */
    public synchronized boolean open(final String path,final int baudRate){
        mSerialPort = new SerialPort(path,baudRate);
        if (!mSerialPort.isSupport()){
            //串口打开失败，请检查串口结点是否正确
            return false;
        }

        mInputStream = mSerialPort.getInputStream();
        mOutputStream = mSerialPort.getOutputStream();

        //读取串口
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                byte[] data = new byte[1024];
                int len = 0;
                try {
                    while (mInputStream!=null){

                        len = mInputStream.read(data);
                        if (len < 0){
                            break;
                        }

                        //正常数据是需要经过拆包和组包的，这里直接打印一下数据
                        System.out.println(HexUtils.toHexString(data,0,len));
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    System.out.println("输入流结束");
                }
            }
        });

        return true;
    }

    /**
     * 往串口写入数据
     * @param data 数据
     * @param offset 偏移量
     * @param size 数据长度
     */
    public synchronized void write(byte[] data,int offset,int size){
        if (mOutputStream != null){
            mThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        mOutputStream.write(data,offset,size);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 关闭串口
     */
    public synchronized void close(){
        if(mSerialPort != null){
            mSerialPort.close();
            mSerialPort = null;
        }

        mOutputStream = null;
        mInputStream = null;
    }

}
